<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1 class="text-center">登录</h1>
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" name="username" id="username" class="form-control">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" name="password" id="password" class="form-control">
            </div>
            <div class="form-group">
                <label for="code">验证码</label>
                <div class="row">
                    <div class="col-md-6">
                        <input type="text" name="code" id="code" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <img id="id_img" src="/get_code/" alt="" height="35px" width="435px">
                    </div>
                </div>
            </div>
            <button id="id_commit" class="btn btn-primary pull-right">登录</button>
            <span id="errors" style="color: red"></span>
        </div>
    </div>
</div>

<script>
    $('#id_commit').click(function () {
        $.ajax({
            url: '',
            type: 'post',
            data: { 'username': $('#username').val(),
                    'password': $('#password').val(),
                    'code': $('#code').val(),
                    csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function (args) {
                if(args.code===1){
                    // 重定向到home
                    window.location.href = args.url
                }else{
                    // 展示报错信息
                    $('#errors').text(args.msg)
                }
            }
        })
    });

    $('#id_img').click(function () {
        // 先获取标签之前的src
        let oldVal = $(this).attr('src')  // /get_code/???
        $(this).attr('src', oldVal+='?')
    })
</script>
</body>
</html>